package fina2.dcs.mail.manager;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.mail.MessagingException;

import org.apache.log4j.Logger;

import fina2.dcs.mail.MailReader;
import fina2.dcs.mail.MailReaderBase;
import fina2.dcs.mail.MailSender;

public class MailRobotImpl implements MailRobot {
	private Logger log = Logger.getLogger(getClass());
	private List<MailUser> mailUsers;

	private MailSender mailSender;

	public MailRobotImpl() {
	}

	public MailRobotImpl(List<MailUser> mailUsers) {
		this.mailUsers = mailUsers;
	}

	@Override
	public List<MailReaderBase> createMailReadSessions() {
		List<MailReaderBase> mailReadersSessions = new ArrayList<MailReaderBase>();
		for (MailUser m : mailUsers) {
			MailReaderBase mailReader = new MailReader(m);
			mailReadersSessions.add(mailReader);
		}
		return mailReadersSessions;
	}

	@Override
	public Map<MailUser, List<AttachInfo>> readMails(List<MailReaderBase> mailReadSessions, Date date) {
		Map<MailUser, List<AttachInfo>> allNewMails = new HashMap<MailUser, List<AttachInfo>>();
		for (MailReaderBase m : mailReadSessions) {
			try {
				List<AttachInfo> list = m.getNewAttahcments(date);
				allNewMails.put(m.getMailUser(), list);
			} catch (MessagingException e) {
				log.error(e.getMessage(), e);
			}
		}
		return allNewMails;
	}

	@Override
	public void sentResponce(String responceString, String subject, String[] cc, String[] bcc, String... to) throws Exception {
		log.info("Statuces Text = \t" + responceString);
		mailSender.send(responceString, subject, cc, bcc, to);
	}

	@Override
	public void connectSender(MailUser mailUser) {
		mailSender = new MailSender(mailUser);
		mailSender.connect();
	}

	@Override
	public boolean isConnectedSender() {
		if (mailSender == null) {
			return false;
		}
		return mailSender.isConected();
	}

	@Override
	public void closeSenderConnection() {
		if (mailSender != null) {
			mailSender.close();
		}
	}

}
